import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86136
 * Date: 2025-05-04
 * Time: 11:12
 */
public class UdpEchoClient {
    private DatagramSocket socket = null;
    //udp本身不保存端的信息，需要在代码中保存一下
    private String serverIp;
    private int serverPort;

    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while(true) {
            //1.从控制台中获取用户输入的内容
            System.out.println("请输入要发送的内容");
            if(!scanner.hasNext()) {
                break;
            }
            String request = scanner.next();
            //2.把请求发送给服务器，需要构造DatagramPacket对象
            //  构造过程中不光要构造载荷还要设置服务器的IP和端口号
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                                            InetAddress.getByName(serverIp),serverPort);//getByName -> UnknownHostException
            //3.发送数据报
            socket.send(requestPacket);//send -> IOException

            //4.接受服务器的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);

            //5.从服务器中读取的数据进行解析，并打印出来
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
